package com.ccloud.api.motorfactory.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ccloud.api.motorfactory.domain.*;
import com.ccloud.api.motorfactory.dto.MotorPartExcelDto;
import com.ccloud.api.motorfactory.mapper.MMotorPartMapper;
import com.ccloud.api.motorfactory.service.*;
import com.ccloud.common.core.constant.BizConstant;
import com.ccloud.common.core.utils.CollectionUtils;
import com.ccloud.common.core.utils.StringUtils;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 摩托零件货品表 服务实现类
 * </p>
 *
 * @author chentl
 * @since 2022-04-09
 */
@Slf4j
@Service
public class MMotorPartServiceImpl extends ServiceImpl<MMotorPartMapper, MMotorPart> implements IMMotorPartService {

    @Resource
    private IMPartApplicationMotorModelRelsService applicationMotorModelRelsService;

    @Resource
    private IMPartAndTypeRelsService partAndTypeRelsService;

    @Resource
    private IMPartMainEngineRelsService mainEngineRelsService;

    @Resource
    private IMApplicationMotorModelService imApplicationMotorModelService;

    @Resource
    private IMPartTypeService partTypeService;

    @Resource
    private IMMainEnginePlantsService mainEnginePlantsService;

    @Override
    public IPage<MMotorPart> selectPage(Page<MMotorPart> page, MMotorPart motorPart) {
        return baseMapper.selectPage(page, motorPart);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveAndBuildRelations(MMotorPart motorPart) {
        save(motorPart);

        buildMotorPartRels(motorPart);
    }


    @Override
    public Map<String, Object> getRelsByPartId(String partId) {
        return baseMapper.getRelsByPartId(partId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateAndReBuildRelations(MMotorPart motorPart) {

        updateById(motorPart);

        Integer motorPartId = motorPart.getId();

        //先全部删除
        clearRels(motorPartId);

        buildMotorPartRels(motorPart);

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveImportData(List<MotorPartExcelDto> list) {
        //查询 partApplicationMotorModel
        List<MApplicationMotorModel> applicationMotorModelList = imApplicationMotorModelService.getMap();
        List<MPartType> partTypeList = partTypeService.getMap();
        List<MMainEnginePlants> mainEnginePlantsList = mainEnginePlantsService.getMap();


        Map<String, String> applicationMotorModelMap = applicationMotorModelList.stream().collect(Collectors.toMap(MApplicationMotorModel::getName, MApplicationMotorModel::getMotorType));
        Map<String, String> partTypeMap = partTypeList.stream().collect(Collectors.toMap(MPartType::getName, MPartType::getPartType));
        Map<String, String> mainEnginePlantMap = mainEnginePlantsList.stream().collect(Collectors.toMap(MMainEnginePlants::getName, MMainEnginePlants::getMainEngineNo));



        List<MPartApplicationMotorModelRels> appRelsInsertList = Lists.newArrayList();
        List<MPartAndTypeRels> partAndTypeInsertList = Lists.newArrayList();
        List<MPartMainEngineRels> mainEnginePlantsInsertList = Lists.newArrayList();
        String specifications;
        for (MotorPartExcelDto excelDto : list) {
            specifications = BizConstant.Specification.reverse(excelDto.getSpecifications());
            MMotorPart motorPart = new MMotorPart();
            BeanUtil.copyProperties(excelDto, motorPart);
            //反显规格
            motorPart.setSpecifications(specifications);
            this.baseMapper.insert(motorPart);
            Integer partId = motorPart.getId();
            log.info("货品信息添加成功,json:{},返回partId:{}", JSON.toJSONString(motorPart), partId);

            //构造 应用车型
            List appRels = motorPart.getPartApplicationMotorModelRels();
            if (CollectionUtils.isNotEmpty(appRels)) {
                appRelsInsertList = (List<MPartApplicationMotorModelRels>) appRels.stream().map(one ->
                        MPartApplicationMotorModelRels.builder()
                                .partId(partId)
                                .motorType(applicationMotorModelMap.get(one.toString()))
                                .build()).filter(one -> !Objects.isNull(((MPartApplicationMotorModelRels) one).getMotorType())).collect(Collectors.toList());

            }
            //构造 货品类型
            List partTypeRels = motorPart.getPartAndTypeRels();
            if (CollectionUtils.isNotEmpty(partTypeRels)) {
                partAndTypeInsertList = (List<MPartAndTypeRels>) partTypeRels.stream().map(one ->
                        MPartAndTypeRels.builder()
                                .partId(partId)
                                .partType(partTypeMap.get(one.toString()))
                                .build()
                ).filter(one -> !Objects.isNull(((MPartAndTypeRels) one).getPartType())).collect(Collectors.toList());
            }

            //构造 主机厂项目
            List mainEngineRels = motorPart.getPartMainEngineRels();
            if (CollectionUtils.isNotEmpty(mainEngineRels)) {
                mainEnginePlantsInsertList = (List<MPartMainEngineRels>) mainEngineRels.stream().map(one ->
                        MPartMainEngineRels.builder()
                                .partId(partId)
                                .mainEngineNo(mainEnginePlantMap.get(one.toString()))
                                .build()
                ).filter(one -> !Objects.isNull(((MPartMainEngineRels) one).getMainEngineNo())).collect(Collectors.toList());
            }

            // 插入
            if (CollectionUtils.isNotEmpty(appRelsInsertList)) {
                applicationMotorModelRelsService.saveBatch(appRelsInsertList);
                log.info("应用车型关联信息已入库");
            }

            if (CollectionUtils.isNotEmpty(partAndTypeInsertList)) {
                partAndTypeRelsService.saveBatch(partAndTypeInsertList);
                log.info("货品类型关联信息已入库");
            }

            if (CollectionUtils.isNotEmpty(mainEnginePlantsInsertList)) {
                mainEngineRelsService.saveBatch(mainEnginePlantsInsertList);
                log.info("主机厂项目关联信息已入库");
            }

            appRelsInsertList.clear();
            partAndTypeInsertList.clear();
            mainEnginePlantsInsertList.clear();

        }


    }

    /**
     * 清理货品所有关联关系
     *
     * @param motorPartId 货品id
     */
    private void clearRels(Integer motorPartId) {
        applicationMotorModelRelsService.remove(
                new LambdaQueryWrapper<MPartApplicationMotorModelRels>().eq(MPartApplicationMotorModelRels::getPartId, motorPartId)
        );
        partAndTypeRelsService.remove(
                new LambdaQueryWrapper<MPartAndTypeRels>().eq(MPartAndTypeRels::getPartId, motorPartId)
        );
        mainEngineRelsService.remove(
                new LambdaQueryWrapper<MPartMainEngineRels>().eq(MPartMainEngineRels::getPartId, motorPartId)
        );
    }

    /**
     * 构造货品关联关系
     *
     * @param motorPart 货品对象
     */
    private void buildMotorPartRels(MMotorPart motorPart) {
        Integer motorPartId = motorPart.getId();
        String selectedMotorType = motorPart.getSelectedMotorType();
        String selectedPartType = motorPart.getSelectedPartType();
        String selectedMainEngine = motorPart.getSelectedMainEngine();

        if (StringUtils.isNotEmpty(selectedMotorType)) {
            List<String> motorTypeList = Arrays.asList(selectedMotorType.split(","));
            List<MPartApplicationMotorModelRels> toInsert = Lists.newArrayList();
            motorTypeList.forEach(type -> {
                MPartApplicationMotorModelRels partApplicationMotorModelRels = new MPartApplicationMotorModelRels();
                partApplicationMotorModelRels.setPartId(motorPartId);
                partApplicationMotorModelRels.setMotorType(type);
                toInsert.add(partApplicationMotorModelRels);
            });
            applicationMotorModelRelsService.saveBatch(toInsert);

        }

        if (StringUtils.isNotEmpty(selectedPartType)) {
            List<String> partTypeList = Arrays.asList(selectedPartType.split(","));
            List<MPartAndTypeRels> toInsert = Lists.newArrayList();

            partTypeList.forEach(type -> {
                MPartAndTypeRels partAndTypeRels = new MPartAndTypeRels();
                partAndTypeRels.setPartId(motorPartId);
                partAndTypeRels.setPartType(type);
                toInsert.add(partAndTypeRels);
            });
            partAndTypeRelsService.saveBatch(toInsert);

        }

        if (StringUtils.isNotEmpty(selectedMainEngine)) {
            List<String> mainEngineList = Arrays.asList(selectedMainEngine.split(","));
            List<MPartMainEngineRels> toInsert = Lists.newArrayList();
            mainEngineList.forEach(mainEngineNo -> {
                MPartMainEngineRels mainEngineRels = new MPartMainEngineRels();
                mainEngineRels.setPartId(motorPartId);
                mainEngineRels.setMainEngineNo(mainEngineNo);
                toInsert.add(mainEngineRels);
            });
            mainEngineRelsService.saveBatch(toInsert);
        }
    }

}
